<template>
  <view class="page">
    <view class="header">
      <text class="alert">⚠</text>
      <text class="title">SOS</text>
      <view class="tools">
        <text class="dot">···</text>
        <text class="cam">◉</text>
      </view>
    </view>

    <view class="hero">
      <view class="ring">
        <view class="btn" @longpress="emergencyCall" @tap="emergencyCall">
          <text class="phone">📞</text>
          <text class="btn-text">紧急呼叫</text>
        </view>
      </view>
      <text class="hint">长按拨号</text>
    </view>

    <view class="panel">
      <text class="panel-title">紧急联系人</text>
      <view v-for="(c,i) in list" :key="c.id" class="item" @longpress="onItemLongPress(c)">
        <view class="left">
          <image class="avatar" src="/static/project/2025-10-14_110352_756.png" />
          <view class="meta">
            <text class="name">{{ c.emergencyContact }}</text>
            <text class="phone-num">{{ c.emergencyPhone }}</text>
          </view>
        </view>
        <view class="right">
          <view class="call" @tap="doCall(c.emergencyPhone)">📞</view>
          <view class="chk" @tap.stop="toggleSelect(c, i)">
            <checkbox :value="String(c.id)" :checked="c.selected" @click.stop="toggleSelect(c, i)"/>
          </view>
          <view class="trash" :class="{ active: c.selected }" @tap.stop="deleteOne(c)">删除</view>
        </view>
      </view>
      <view class="add-wrap">
        <view class="add-btn" @tap="showAdd=true">＋ 添加联系人</view>
      </view>
      <view class="bulk" v-if="selectedIds.length">
        <button class="del" @tap="bulkDelete">删除所选 ({{ selectedIds.length }})</button>
      </view>
    </view>

    <view v-if="showAdd" class="overlay">
      <view class="dialog">
        <text class="dlg-title">添加紧急联系人</text>
        <view class="dlg-field">
          <text class="dlg-label">姓名</text>
          <input class="dlg-input" v-model="form.name" placeholder="输入联系人姓名" />
        </view>
        <view class="dlg-field">
          <text class="dlg-label">电话号码</text>
          <input class="dlg-input" v-model="form.phone" placeholder="输入联系电话" />
        </view>
        <view class="dlg-actions">
          <button class="dlg-btn ghost" @tap="showAdd=false">取消</button>
          <button class="dlg-btn" @tap="saveAdd">保存</button>
        </view>
      </view>
    </view>
    <custom-tabbar :active="0" />
  </view>
  
</template>

<script>
import { listEmergency, addEmergency, deleteEmergency } from '@/api/emergency'
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import store from '@/store'
export default {
  components: { CustomTabbar },
  data(){
    return { 
      list: [], 
      showAdd:false, 
      form:{ name:'', phone:'' }, 
      selectedIds: [] 
    }
  },
  onShow(){ 
    this.selectedIds = []
    this.fetch() 
  },
  computed: {
    selectedIdsSet() {
      return new Set(this.selectedIds)
    }
  },
  methods: {
    async fetch(){
      const uid = store.getters && store.getters.id
      const res = await listEmergency({ userId: uid })
      const rows = Array.isArray(res.data) ? res.data : (res.rows || res.list || [])
      this.list = rows.map(r=>({ 
        id: r.id, 
        emergencyContact: r.emergencyContact || r.name, 
        emergencyPhone: r.emergencyPhone || r.phone,
        selected: false  // 明确初始化为 false
      }))
      console.log('fetch completed, list:', this.list)
    },
    emergencyCall(){
      if (!this.list.length) return
      this.doCall(this.list[0].emergencyPhone)
    },
    doCall(phone){
      if (!phone) return
      uni.makePhoneCall({ phoneNumber: String(phone) })
    },
    async saveAdd(){
      const name = String(this.form.name||'').trim()
      const phone = String(this.form.phone||'').trim()
      if (!name || !phone) { this.$modal && this.$modal.showToast('请填写姓名和电话'); return }
      if (!/^\d{11}$/.test(phone)) { this.$modal && this.$modal.showToast('手机号需为11位数字'); return }
      const uid = store.getters && store.getters.id
      const r = await addEmergency({ userId: uid, emergencyContact: name, emergencyPhone: phone })
      if ((r && r.code) === 200) { this.$modal && this.$modal.showToast('添加成功'); this.form={name:'',phone:''}; this.showAdd=false; this.fetch() }
    },
    onItemLongPress(c){
      if (!c || !c.id) return
      uni.showModal({
        title: '删除联系人',
        content: `确认删除 ${c.emergencyContact} 吗？`,
        confirmColor: '#ef4444',
        success: async (res)=>{
          if (!res.confirm) return
          try{
            const r = await deleteEmergency(c.id)
            if ((r && r.code) === 200) { this.$modal && this.$modal.showToast('已删除'); this.fetch() }
          }catch(e){}
        }
      })
    },
    toggleSelect(c, index){
      if (!c || !c.id) {
        console.log('toggleSelect: 没有找到id', c)
        return
      }
      console.log('toggleSelect BEFORE: index=', index, 'id=', c.id, 'selected=', c.selected)
      
      // 使用 Vue.set 或 $set 来确保响应式更新
      const newSelected = !c.selected
      this.$set(this.list[index], 'selected', newSelected)
      
      // 同步到 selectedIds 数组
      const idx = this.selectedIds.indexOf(c.id)
      if (newSelected && idx < 0) {
        this.selectedIds.push(c.id)
      } else if (!newSelected && idx >= 0) {
        this.selectedIds.splice(idx, 1)
      }
      
      console.log('toggleSelect AFTER: index=', index, 'id=', c.id, 'selected=', this.list[index].selected, 'selectedIds=', this.selectedIds)
    },
    isSelected(id){ 
      const result = this.selectedIds.indexOf(id) >= 0
      console.log('isSelected check: id=', id, 'result=', result, 'selectedIds=', this.selectedIds)
      return result
    },
    async deleteOne(c){
      if (!c || !c.id) return
      if (!c.selected) { 
        this.$modal && this.$modal.showToast('请先勾选该联系人')
        return 
      }
      uni.showModal({
        title: '确认删除',
        content: `确认删除联系人 ${c.emergencyContact} 吗？`,
        confirmColor: '#ef4444',
        success: async (res) => {
          if (!res.confirm) return
          try {
            const r = await deleteEmergency(c.id)
            if ((r && r.code) === 200) {
              this.selectedIds = this.selectedIds.filter(id=>id!==c.id)
              this.$modal && this.$modal.showToast('删除成功')
              this.fetch()
            }
          } catch (e) {
            this.$modal && this.$modal.showToast('删除失败')
          }
        }
      })
    },
    async bulkDelete(){
      if (!this.selectedIds.length) return
      uni.showModal({
        title:'批量删除',
        content:`确认删除选中的 ${this.selectedIds.length} 位联系人吗？`,
        confirmColor:'#ef4444',
        success: async (res)=>{
          if (!res.confirm) return
          try{
            for (const id of this.selectedIds) { await deleteEmergency(id) }
            this.selectedIds = []
            this.fetch()
            this.$modal && this.$modal.showToast('已删除')
          }catch(e){}
        }
      })
    },
    goHome(){ uni.reLaunch({ url: '/pages/index' }) }
  }
}
</script>

<style scoped>
.page { padding: 16rpx 16rpx 120rpx 16rpx; background:#f7fafc; }
.header { display:flex; align-items:center; justify-content: space-between; }
.alert { color:#ef4444; font-size: 36rpx; }
.back { color:#374151; font-size: 44rpx; padding: 6rpx 8rpx; }
.title { font-size: 34rpx; font-weight: 700; }
.tools { color:#6b7280; }
.hero { display:flex; flex-direction: column; align-items:center; margin: 20rpx 0; }
.ring { width: 260rpx; height: 260rpx; border-radius: 130rpx; background: radial-gradient(circle at 50% 50%, #f87171 0%, #ef4444 60%); box-shadow: 0 12rpx 36rpx rgba(239,68,68,.35); border: 10rpx solid #fde047; display:flex; align-items:center; justify-content:center; }
.btn { width: 220rpx; height: 220rpx; border-radius: 110rpx; background: transparent; color:#fff; display:flex; flex-direction: column; align-items:center; justify-content:center; }
.phone { font-size: 48rpx; }
.btn-text { margin-top: 6rpx; font-weight: 700; }
.hint { color:#9ca3af; margin-top: 8rpx; }
.panel { background:#fff; border-radius: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06); padding: 16rpx; }
.panel-title { font-weight:700; margin-bottom: 12rpx; display:block; }
.item { display:flex; align-items:center; justify-content: space-between; background:#fff; border-radius: 12rpx; padding: 12rpx; margin-bottom: 10rpx; box-shadow: 0 4rpx 14rpx rgba(0,0,0,.05); }
.left { display:flex; align-items:center; }
.avatar { width: 64rpx; height: 64rpx; border-radius: 50%; background:#f3f4f6; }
.meta { margin-left: 10rpx; }
.name { font-weight:600; }
.phone-num { color:#6b7280; font-size: 22rpx; }
.right .call { width: 72rpx; height: 72rpx; border-radius: 36rpx; background:#10b981; color:#fff; display:flex; align-items:center; justify-content:center; }
.right { display:flex; align-items:center; gap: 12rpx; }
.chk { transform: scale(0.9); }
.trash { 
  background:#f3f4f6; 
  color:#9ca3af; 
  border:none; 
  padding: 10rpx 16rpx; 
  border-radius: 10rpx; 
  min-width: 88rpx; 
  text-align:center;
  font-size: 24rpx;
  transition: all 0.3s ease;
}
.trash.active { 
  background:#ef4444 !important; 
  color:#fff !important;
  font-weight: 600 !important;
}
.bulk { display:flex; justify-content:center; margin-top: 16rpx; }
.bulk .del { 
  background:#ef4444; 
  color:#fff; 
  border:none; 
  padding: 20rpx 48rpx; 
  border-radius: 16rpx; 
  font-size: 30rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 24rpx rgba(239, 68, 68, 0.3);
}
.add-wrap { display:flex; justify-content:center; margin-top: 8rpx; }
.add-btn { background:#ecfeff; color:#0ea5a5; border:none; padding: 12rpx 18rpx; border-radius: 999rpx; }
.overlay { position: fixed; left:0; right:0; top:0; bottom:0; background: rgba(0,0,0,.45); display:flex; align-items:center; justify-content:center; z-index: 999; }
.dialog { width: 700rpx; background:#fff; border-radius: 16rpx; padding: 24rpx; }
.dlg-title { font-weight: 700; margin-bottom: 16rpx; display:block; font-size: 32rpx; }
.dlg-field { margin-bottom: 16rpx; }
.dlg-label { display:block; color:#6b7280; font-size: 24rpx; margin-bottom: 8rpx; }
.dlg-input { width:100%; background:#f5f6f7; border-radius: 12rpx; padding: 0 24rpx; font-size: 30rpx; height: 84rpx; line-height: 84rpx; box-sizing: border-box; }
.dlg-actions { display:flex; justify-content:flex-end; gap: 16rpx; margin-top: 12rpx; }
.dlg-btn { background:#0ea5a5; color:#fff; border:none; padding: 14rpx 24rpx; border-radius: 12rpx; font-size: 28rpx; }
.dlg-btn.ghost { background:#f3f4f6; color:#374151; }
</style>


